<?php

namespace App\Http\Controllers\Admin;

use App\Http\Common\Lib\Common;
use App\Models\AdminUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    /**
     * 登陆页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View|\think\response\Redirect|\think\response\View
     */
    public function index(Request $request){
        $user = $request->session()->get('adminUser',null);
        if($user && $user->expire_in > time()){
            return redirect('admin/admin');
        }
        return view('admin.login.index');
    }

    /**
     * 登陆操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $account = $request->input('account','');
        $password = $request->input('password','');
        $userModel = new AdminUser();
        $res = $userModel->login($account,$password);
        if($res['status'] == config('statusInfo.status.success')){
            $user = $res['data'];
            $now = time();
            $user->refresh_time = $now + config('systemSetting.admin.adminRefreshTime',3600);
            $user->expire_in = $now + config('systemSetting.admin.adminExpireTime',36000);
            $request->session()->put('adminUser',$user);
        }
        return response()->json(Common::dataFormat($res['status'],$res['msg']));
    }

    /**
     * 登出
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\think\response\Redirect
     */
    public function logout(Request $request){
        $request->session()->flush();
        return redirect('admin/login');
    }
}
